package com.ygqh.baby.controller;

import java.util.Collection;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONPObject;

@Component
@Aspect
public class DbPersistenceAspect {

	/**
	 * 配置切入点
	 */
	@Pointcut("@annotation(com.ygqh.baby.annotation.YgController)")
	public void allController() {
	}

	@Pointcut("execution(public * com.ygqh.baby.service.*.*(..))")
	public void allService() {
	}

	/**
	 * 配置抛出异常后通知
	 * 
	 * @param joinPoint
	 * @param ex
	 */
	@AfterReturning(value = "allController()", argNames = "retVal", returning = "retVal")
	public void before(JoinPoint joinPoint, Object retVal) throws Throwable {
		if (retVal == null)
			return;
		Class<?> clz = retVal.getClass();
		if (Collection.class.isAssignableFrom(clz)) {
			Collection<?> col = (Collection<?>) retVal;
			for (Object val : col) {
				assembleValue(val);
			}
		}
		if (JSONPObject.class.isAssignableFrom(clz)) {

		}

	}

	/**
	 * 配置返回后通知
	 * 
	 * @param joinPoint
	 * @param retVal
	 * @return
	 * @throws Throwable
	 */
//	@AfterReturning(value = "allService()", argNames = "retVal", returning = "retVal")
	public void afterReturningFind(JoinPoint joinPoint, Object retVal) throws Throwable {
		assembleValue(retVal);
	}

	private void assembleValue(Object obj) {
		if (obj == null)
			return;
		Class<?> clz = obj.getClass();
		if (Collection.class.isAssignableFrom(clz)) {
			Collection<?> col = (Collection<?>) obj;
			for (Object val : col) {
				assembleValue(val);
			}
		}

	}
}
